package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import common.Pager;
import dao.CourseDAO;
import dao.RoomDAO;
import dao.StudentDAO;
import dao.TeacherDAO;
import model.Course;
import model.Room;
import model.Student;
import model.Teacher;

public class CourseAction extends ActionSupport {
	
	CourseDAO dao=new CourseDAO();
	TeacherDAO tDao=new TeacherDAO();
	RoomDAO rDao=new RoomDAO();
	private Course course;
	private Teacher teacher;
	private Room room;
	private int page;
	
	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}
	
	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public Room getRoom() {
		return room;
	}

	public void setRoom(Room room) {
		this.room = room;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String main() {	
		prepareData();
		return "coursemain";
	}
	
	private void prepareData() {
		HttpServletRequest req=ServletActionContext.getRequest();
		//保存、显示课程的所有信息
		if(page==0) {
			page=1;
		}
		
		Pager pager=new Pager();
		dao.initPage(pager);//拿到了最新的总页数
		//|如果当前页大于总页数，则等于总页数
		if(page>pager.getPageCount()) {	//防删除最后一条数据，传过来的page是已不存在的
			page=pager.getPageCount();
		}
		if(ServletActionContext.getContext().get("ADD")!=null) {//添加用户，使跳转在最新的一页
			page=pager.getPageCount();
		}
		pager.setPageNo(page);//归类
		StringBuilder str=new StringBuilder();//变量String,可先保存，后一次性打印
		List<Course> list=dao.getCourses(pager);
				
		if(list.size()>0) {
			ActionContext tex=ServletActionContext.getContext();
			tex.put("TEACHERS",tDao.getTeachers());
			tex.put("ROOMS", rDao.getrooms());
			tex.put("COURSES", list);
			
			//构建、显示导航按钮
			int btns=pager.getBtnCount();//得到当前页的所有页数按钮
			btns=btns/2;//把当前页的所有按钮平均分
				//|page是用户选择的按钮，start和end加起来等于当页的所有按钮
			int start=page-btns;//在当前按钮的找按钮的到开始点
			int end=page+btns;//..找到..终点
						
			if(start<1) {
				start=1;
				end=start+2*btns;//start<1 使后面得到扩展
			}
			if(end>pager.getPageCount()) {
				end=pager.getPageCount();
				start=end-2*btns;//end>pager.getPageCount() 后面无法继续加，使前面得到增加
			}
			if(start<1) {
				start=1;
			}
			for(int i=start;i<=end;i++) {
					//|当用户点击某个按钮时，把点击的参数page传过去
				str.append("<a href='"+req.getContextPath()+"/course/main?page="+i+"'>");
					//|区别当前点击的按钮和其他按钮
				if(i==page) {
					str.append("<font color='red'><b>");
					str.append(i);
					str.append("</b></font>");
				}
				else {
					str.append(i);
				}
				str.append("</a>");
				str.append("&nbsp;&nbsp;");
			}
			str.append("<br/>");
			tex.put("NAVBAR", str.toString());
		}
	}
	
	public String imain() {
		prepareData();
		return "initmain";
	}
	
	public String cmain() throws IOException {
		
		//未登录，跳转登录页面
	//方法一：
/*		Object object=ActionContext.getContext().getSession().get("STUDETN");
		if(object==null) {
			HttpServletResponse response=ServletActionContext.getResponse();
			HttpServletRequest request=ServletActionContext.getRequest();
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return null;
		}
*/
	//方法二：
		HttpServletResponse response=ServletActionContext.getResponse();
		HttpServletRequest request=ServletActionContext.getRequest();
		Object object=request.getSession().getAttribute("STUDENT");
		if(object==null) {
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return null;
		}
		prepareData();
		return "choosemain";		
	}
	
	private String updateit() {
		if(course.getId()==0) {//判断是修改还是添加
			ServletActionContext.getContext().put("ADD", true);
		}
		dao.update(course);
		return main();
	}

	public String update() {//修改和添加
		return updateit();
	}

	public String modify() {
		return updateit();
	}
	
	//删除教室
	public String delete() {
		dao.delete(course);
		return null;
	}
	
	//得到id-得到、修改课程
	public String get() {
		course=dao.get(course);
		HttpServletResponse res=ServletActionContext.getResponse();
		res.setCharacterEncoding("utf-8");//使用过滤器，注解的方式不好用，web.xml
		try {			
			PrintWriter out=res.getWriter();
			out.print(course.getId()+"!"+course.getName()+"!"+course.getType()+"!"+course.getHours());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	//接收传来的course.id和teacher.id
	public String updateTeacher() {
		
		teacher=tDao.get(teacher);
		course=dao.get(course);
		course.setTeacher(teacher);
		dao.update(course);//更新保存在数据库
		return null;
	}
	
	public String updateroom() {
		room=rDao.get(room);
		course=dao.get(course);
		course.setRoom(room);
		dao.update(course);
		return null;
	}
	
	public String checkselect() throws IOException {
		Student student=(Student) ActionContext.getContext().getSession().get("STUDENT");
		Set<Course> courses=student.getCourses();
		Iterator<Course> iterator=courses.iterator();
		boolean flag=false;
		while(iterator.hasNext()) {
			Course currentcourse=iterator.next();
			if(currentcourse.getId()==course.getId()) {
				flag=true;
			}
		}
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter out=response.getWriter();
		out.print(flag);
		return null;
	}
	
	public String checkit() throws IOException {
		Student student=(Student) ActionContext.getContext().getSession().get("STUDENT");
		StudentDAO sDao=new StudentDAO();

	//使student和数据库关联
		student=sDao.get(student);
		course=dao.get(course);
		
		Set<Course> courses=student.getCourses();
		Iterator<Course> iterator=courses.iterator();
		boolean flag=false;
		Course currentcourse=null;
		while(iterator.hasNext()) {
			currentcourse=iterator.next();
			if(currentcourse.getId()==course.getId()) {
				flag=true;
			}
		}
		if(flag) {//有，删除
			student.getCourses().remove(currentcourse);
		}else {//没有，选择
			student.getCourses().add(course);
		}
		sDao.update(student);
		return null;
	}
}
